import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './entities/category.entity';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepository: Repository<Category>,
  ) {}

  async create(createCategoryDto: CreateCategoryDto): Promise<Category> {
    // 检查分类名称是否已存在
    const existingCategory = await this.categoryRepository.findOne({
      where: { name: createCategoryDto.name },
    });

    if (existingCategory) {
      throw new ConflictException(`分类名称"${createCategoryDto.name}"已存在`);
    }

    const category = this.categoryRepository.create(createCategoryDto);
    return this.categoryRepository.save(category);
  }

  async findAll(): Promise<Category[]> {
    return this.categoryRepository.find({
      order: { sortOrder: 'ASC', createdAt: 'DESC' },
    });
  }

  async findOne(id: string): Promise<Category> {
    const category = await this.categoryRepository.findOne({
      where: { id },
      relations: ['books'],
    });
    
    if (!category) {
      throw new NotFoundException(`ID为${id}的分类不存在`);
    }
    
    return category;
  }

  async update(id: string, updateCategoryDto: UpdateCategoryDto): Promise<Category> {
    const category = await this.findOne(id);

    // 如果更新分类名称，检查新名称是否已被其他分类使用
    if (updateCategoryDto.name && updateCategoryDto.name !== category.name) {
      const existingCategory = await this.categoryRepository.findOne({
        where: { name: updateCategoryDto.name },
      });

      if (existingCategory) {
        throw new ConflictException(`分类名称"${updateCategoryDto.name}"已存在`);
      }
    }

    // 更新分类信息
    Object.assign(category, updateCategoryDto);
    return this.categoryRepository.save(category);
  }

  async remove(id: string): Promise<void> {
    const category = await this.findOne(id);
    await this.categoryRepository.remove(category);
  }

  // 添加示例数据
  async addSampleCategories(): Promise<Category[]> {
    const sampleCategories = [
      {
        name: '科技',
        description: '包含各类科技相关书籍',
        sortOrder: 1,
        isActive: true,
      },
      {
        name: '文学',
        description: '包含各类文学作品',
        sortOrder: 2,
        isActive: true,
      },
      {
        name: '历史',
        description: '包含各类历史相关书籍',
        sortOrder: 3,
        isActive: true,
      },
    ];

    const categories: Category[] = [];
    
    for (const categoryData of sampleCategories) {
      // 检查分类名称是否已存在
      const existingCategory = await this.categoryRepository.findOne({
        where: { name: categoryData.name },
      });

      if (!existingCategory) {
        const category = this.categoryRepository.create(categoryData);
        categories.push(await this.categoryRepository.save(category));
      }
    }

    return categories;
  }
}
